<template>
  <!-- 合同模板-预览/编辑 -->
  <div class="templatePreviewPage">
    <CommonTitle
      :titleName="`${
        getPropertyType == 1
          ? '综合体'
          : getPropertyType == 2
          ? '农贸市场'
          : '商铺'
      }租赁合同模板 —— ${getPageType == 'preview' ? '预览' : '编辑'}`"
    >
      <template #rightCnBox>
        <el-divider direction="vertical" style="height: 18px; margin: 0 12px" />
        <div class="versionBox">模板版本号：{{ getVersion }}</div>
      </template>
    </CommonTitle>
    <div class="contentBox">
      <!-- 需要后端返回响应头 charset 为 gb2312 ，不然会乱码 -->
      <div
        class="leftBox"
        :style="rightBoxState.hideRightBoxFlag ? 'margin-right:0' : 'width: 50%'"
      >
        <div
          class="previewBox"
          v-if="getPageType == 'preview'"
          v-html="state.ctx"
        >
        </div>
        <div class="editBox" v-else>
          <BaseEditor
            :getHtmlContent="state.ctx"
            :excludeArr="state.editorExcludeArr"
            getHight="800px"
            @getEditorVal="getEditorVal"
          />
        </div>
      </div>
      <div
        class="rightBox"
        :class="
          rightBoxState.hideRightBoxFlag ? 'hideRightWidth' : 'showRightWidth'
        "
      >
        <div
          class="ctrlBtnBox"
          :class="rightBoxState.hideRightBoxFlag ? 'toLeftBtn' : 'toRightBtn'"
          @click="doControlRight"
        >
          <el-icon :size="20" v-if="!rightBoxState.hideRightBoxFlag"
            ><ArrowRight
          /></el-icon>
          <el-icon :size="20" v-else><ArrowLeft /></el-icon>
        </div>
        <div
          class="formHeadBox"
          :style="
            rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : ''
          "
        >
          固定参数设置
        </div>
        <el-form
          :model="infoForm"
          label-width="110px"
          :rules="formRules.rules"
          :style="
            rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
              ? 'display:none'
              : ''
          "
        >
          <el-form-item label="竞租方式">
            <el-select
              v-model="infoForm.competeType"
              class="selectStyle"
              placeholder="请选择"
              @change="competeTypeChange"
              :disabled="inputDisableFlag"
            >
              <el-option
                v-for="item in competeTypeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="租赁的资产">
            <el-input
              v-model="infoForm.leaseAsset"
              class="inputStyle"
              :class="inputDisableFlag ? '' : 'inputCursor'"
              placeholder="点击选择"
              readonly
              @click="showAssetDialog"
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="租赁的房源">
            <el-input
              v-model="infoForm.leaseHousing"
              class="inputStyle"
              :class="inputDisableFlag ? '' : 'inputCursor'"
              placeholder="点击选择"
              readonly
              @click="showHousingDialog"
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <!-- 选择的房源列表 -->
          <div class="housesListBox" v-if="infoForm.selectedHousesArr.length">
            <el-form-item
              class="housesItemStyle"
              v-for="(n, i) in infoForm.selectedHousesArr"
              :key="i"
              :label="`房源${i + 1}`"
            >
              <img
                class="deletBtn"
                src="@/assets/iconImg/delet.png"
                alt=""
                @click="doDeletHousesList(i)"
              />
              <el-input v-model="n.housingNumber" disabled />
              <el-input v-model="n.area" disabled />
            </el-form-item>
          </div>
          <el-form-item label="租赁面积">
            <el-input
              v-model="infoForm.leaseArea"
              placeholder="点击选择"
              disabled
            />
          </el-form-item>
          <el-form-item class="limitInput" label="租赁期限" prop="monthVal">
            <el-date-picker
              v-model="infoForm.leaseDate"
              class="dateInputBox"
              type="daterange"
              value-format="YYYY-MM-DD"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :disabled-date="disabledDate"
              size="large"
              :disabled="inputDisableFlag"
              @change="onSignTimeChange"
            >
            </el-date-picker>
            <el-input
              v-model="infoForm.monthVal"
              class="inputStyle"
              placeholder="月"
              style="width: 45px"
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="免租期">
            <el-input
              v-model="infoForm.freeMonth"
              class="inputStyle"
              placeholder="月数（单位：月）"
              clearable
              @input="
                infoForm.freeMonth = limitInputNum(
                  infoForm.freeMonth,
                  10,
                  0,
                  false
                )
              "
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="经营用途">
            <el-input
              v-model="infoForm.usingFor"
              class="inputStyle"
              maxlength="32"
              placeholder="请输入用途"
              clearable
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="租金单价" prop="unitPrice">
            <el-input
              v-model="infoForm.unitPrice"
              class="inputStyle"
              placeholder="请输入金额（单位：元/㎡/月）"
              clearable
              @input="
                infoForm.unitPrice = limitInputNum(
                  infoForm.unitPrice,
                  9,
                  2,
                  true
                )
              "
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="递增模式和比例" class="modeItemBox">
            第
            <el-form-item label="" prop="modeYear">
              <el-input
                v-model="infoForm.modeYear"
                class="inputStyle"
                placeholder="N"
                @input="
                  infoForm.modeYear = limitInputNum(
                    infoForm.modeYear,
                    3,
                    0,
                    false
                  )
                "
                :disabled="inputDisableFlag"
              />
            </el-form-item>
            年后，逐年递增
            <el-form-item label="" prop="modeRatio">
              <el-input
                v-model="infoForm.modeRatio"
                class="inputStyle"
                placeholder="%"
                @input="
                  infoForm.modeRatio = limitInputNum(
                    infoForm.modeRatio,
                    3,
                    0,
                    false
                  )
                "
                :disabled="inputDisableFlag"
              />%
            </el-form-item>
          </el-form-item>
          <el-form-item label="付款方式">
            <el-select
              v-model="infoForm.payType"
              class="selectStyle"
              placeholder="请选择"
              @change="payTypeChange"
              :disabled="inputDisableFlag"
            >
              <el-option
                v-for="item in payTypeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物业管理费" prop="propertyFee">
            <el-input
              v-model="infoForm.propertyFee"
              class="inputStyle"
              placeholder="请输入金额（单位：元/㎡/月）"
              clearable
              @input="
                infoForm.propertyFee = limitInputNum(
                  infoForm.propertyFee,
                  9,
                  2,
                  true
                )
              "
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="保证金" prop="earnestMoney">
            <el-input
              v-model="infoForm.earnestMoney"
              class="inputStyle"
              placeholder="请输入金额（单位：元/㎡/月）"
              clearable
              @input="
                infoForm.earnestMoney = limitInputNum(
                  infoForm.earnestMoney,
                  9,
                  2,
                  true
                )
              "
              :disabled="inputDisableFlag"
            />
          </el-form-item>
          <el-form-item label="新签/续签">
            <el-select
              v-model="infoForm.signType"
              class="selectStyle"
              placeholder="请选择"
              @change="signTypeChange"
              :disabled="inputDisableFlag"
            >
              <el-option
                v-for="item in signTypeOptionsArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="infoForm.signType == 1" label="保证金缴纳年份">
            <el-input
              v-model="infoForm.depositYear"
              class="inputStyle"
              placeholder="请输入年份（单位：年）"
            />
          </el-form-item>
          <el-form-item v-if="getPageType == 'edit'" style="margin-top: 28px">
            <el-button
              color="#FF7B50"
              style="color: #fff; width: 68px; height: 31px; margin: 0 auto"
              type="primary"
              @click="doEditSubmit"
              >保存</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <SelectLeaseAssetDialog
      ref="LeaseAssetDialogRef"
      @getAssetId="getAssetId"
    />
    <SelectLeaseHouseDialog
      ref="LeaseHouseDialogRef"
      @getHouseInfo="getHouseInfo"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import BaseEditor from "@/components/BaseEditor";
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElDivider,
  ElDatePicker,
  ElInputNumber,
} from "element-plus";
import { ArrowRight, ArrowLeft } from "@element-plus/icons-vue";
import {
  competeTypeOptionsArr,
  payTypeOptionsArr,
  signTypeOptionsArr,
} from "@/common/dict/dictCollect";
import dayjs from "dayjs";
import { limitInputNum } from "@/common/utils/GlobalUtils";
import CommonTitle from "@/components/CommonTitle.vue";
import SelectLeaseAssetDialog from "./components/selectLeaseAssetDialog.vue";
import SelectLeaseHouseDialog from "./components/selectLeaseHouseDialog.vue";
import { useRoute, useRouter } from "vue-router";
import { contractApi } from "@/api/assets";

const route = useRoute();
const router = useRouter();

// 从路由path中获取的
const getPageType = router.currentRoute.value.params.pageType;
const getTemplateName = router.currentRoute.value.params.templateName;
const getTemplateUrlKey = router.currentRoute.value.params.templateUrlKey;
// 物业类型（1综合体 2农贸市场 3商铺）
const getPropertyType = router.currentRoute.value.params.propertyType;
// 协议类型（1资产租赁）
const getProtocolType = router.currentRoute.value.params.protocolType;
// 业务场景（1新签 2 续签 3退租）
const getContractType = router.currentRoute.value.params.contractType;
// 版本号
const getVersion = router.currentRoute.value.params.version;

// 输入框禁用
const inputDisableFlag = getPageType == "preview" ? false : true;

const state = reactive({
  ctx: null,
  assetId: "",
  editorExcludeArr: ["group-image", "group-video", "emotion"],
  getHtml: "",
});

const initInfo = () => {
  contractApi.contractPreview(getTemplateUrlKey).then((res) => {
    state.ctx = res;
  });
};

// form相关
const infoForm = reactive({
  competeType: "",
  leaseAsset: "请选择",
  leaseHousing: "请选择",
  leaseArea: "",
  freeMonth: "",
  usingFor: "",
  unitPrice: null,
  payType: "",
  propertyFee: "",
  earnestMoney: "",
  signType: "",
  leaseDate: "",
  monthVal: "",
  modeYear: "",
  modeRatio: "",
  depositYear: "",
  selectedHousesArr: [],
});

// 计算间隔几个月
// const date1 = dayjs('2019-01-25')
// const date2 = dayjs('2018-06-05')
// date1.diff(date2, 'month') // 7

// form校验相关
const checkPrice = (rule, value, callback) => {
  if (value) {
    if (value <= 0 || value >= 1000000000) {
      callback(new Error("输入值应为 0-999999999.99 之间的数字"));
      return;
    } else {
      if (value.indexOf(".") >= 0) {
        if (!value.split(".")[1]) {
          callback(new Error("格式有误"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
  } else {
    callback();
  }
};
const checkMonth = (rule, value, callback) => {
  if (value) {
    if (value < 0 || value > 1200) {
      callback(new Error("月份数应在 0-1200 之间"));
      return;
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const checkYear = (rule, value, callback) => {
  if (value) {
    if (value < 0 || value > 120) {
      callback(new Error("应在 0-120 之间"));
      return;
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const checkRatio = (rule, value, callback) => {
  if (value) {
    if (value < 0 || value > 100) {
      callback(new Error("应在 0-100 之间"));
      return;
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const formRules = reactive({
  rules: {
    unitPrice: [{ validator: checkPrice, trigger: "blur" }],
    propertyFee: [{ validator: checkPrice, trigger: "blur" }],
    earnestMoney: [{ validator: checkPrice, trigger: "blur" }],
    monthVal: [{ validator: checkMonth, trigger: "blur" }],
    modeYear: [{ validator: checkYear, trigger: "blur" }],
    modeRatio: [{ validator: checkRatio, trigger: "blur" }],
  },
});
const competeTypeChange = (val) => {
  console.log(val);
};

//租赁开始/结束时间
const onSignTimeChange = (value) => {
  if (value && value !== "") {
    // form.signStartTime = value[0];
    // form.signEndTime = value[1];
    // 计算间隔月数
    const date1 = dayjs(value[0]);
    const date2 = dayjs(value[1]);
    infoForm.monthVal = date2.diff(date1, "month", true).toFixed(1);
  }
};

// 付款方式选择
const payTypeChange = () => {};

// 签约类型选择
const signTypeChange = (val) => {};

// 资产弹窗
const LeaseAssetDialogRef = ref(null);
const showAssetDialog = () => {
  LeaseAssetDialogRef.value.open();
};
const getAssetId = (val) => {
  console.log(val.assetsId);
  state.assetId = val.assetsId;
  infoForm.leaseAsset = val.assetsName;
};

// 房源弹窗
const LeaseHouseDialogRef = ref(null);
const showHousingDialog = () => {
  LeaseHouseDialogRef.value.open(state.assetId);
};
const getHouseInfo = (val) => {
  infoForm.selectedHousesArr.push(val);
};

// 房源列表删除
const doDeletHousesList = (index) => {
  infoForm.selectedHousesArr.splice(index, 1);
};

// 最早可选2019年
const disabledDate = (time) => {
  return dayjs(time) < dayjs("2019-1-1");
};

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

const getEditorVal = (val) => {
  state.getHtml = val;
};

const doEditSubmit = () => {
  let params = {
    html: state.getHtml,
    fileName: getTemplateName,
    version: getVersion,
    protocolType: getProtocolType,
    contractType: getContractType,
    propertyType: getPropertyType,
  };
  contractApi.contractUpdate(params).then((res) => {});
};

onMounted(() => {
  initInfo();
});
</script>

<style lang="scss" scoped>
.templatePreviewPage {
  .versionBox {
    height: 20px;
    line-height: 25px;
  }
  .contentBox {
    display: flex;
    .leftBox {
      flex: 1;
      height: 92vh;
      margin-right: 40px;
      // overflow: hidden;
      .previewBox {
        height: 100%;
        border: 1px solid #e3e7f1;
        border-radius: 10px;
        overflow-y: auto;
      }
    }
    .rightBox {
      // width: 428px;
      border-left: 5px solid $title-sm-color;
      border-radius: 10px;
      padding: 30px 0 30px 40px;
      position: relative;
      .ctrlBtnBox {
        width: 34px;
        height: 86px;
        line-height: 94px;
        text-align: center;
        padding-left: 10px;
        background: url("@/assets/iconImg/arrowbox.png") no-repeat;
        background-size: cover;
        position: absolute;
        top: 290px;
        cursor: pointer;
      }
      .toRightBtn {
        left: -39px;
      }
      .toLeftBtn {
        left: 14px;
      }
      .formHeadBox {
        font-size: 16px;
        font-family: SourceHanSansMedium;
        color: #1a1a1a;
        margin-bottom: 26px;
      }
    }
    .showRightWidth {
      width: 428px;
      transition: all 0.6s;
    }
    .hideRightWidth {
      width: 0px;
      padding-left: 0;
      border-left: none;
      transition: all 0.6s;
    }
  }
}
</style>

<style lang="scss" scoped>
.templatePreviewPage {
  .contentBox {
    .rightBox {
      :deep(.el-form) {
        .el-form-item {
          margin-bottom: 21px;
          .el-form-item__content {
            .selectStyle {
              width: 100%;
              .select-trigger {
                .el-input__wrapper {
                  box-shadow: 0 0 0 1px $input-focus-bd-color inset;
                }
              }
            }
            .inputStyle {
              width: 100%;
              .el-input__wrapper {
                background-color: #fff8f6;
                box-shadow: 0 0 0 1px $input-focus-bd-color inset;
                .el-input__inner {
                  text-align: center;
                }
              }
            }
            .inputCursor {
              .el-input__wrapper {
                .el-input__inner {
                  cursor: pointer;
                }
              }
            }
          }
        }
        .modeItemBox {
          .el-form-item__content {
            .el-form-item {
              margin-bottom: 0;
              .el-form-item__content {
                .el-input {
                  width: 54px;
                  margin: 0 10px;
                }
              }
            }
          }
        }
        .limitInput {
          .el-form-item__content {
            display: flex;
            .dateInputBox {
              flex: 1;
              margin-right: 6px;
              .el-input__wrapper {
                box-shadow: 0 0 0 1px $input-focus-bd-color inset;
              }
            }
            .el-input {
              width: 100px;
            }
          }
        }
        .el-input {
          height: 40px;
        }
      }
      :deep(.housesListBox) {
        .housesItemStyle {
          position: relative;
          .el-form-item__content {
            display: flex;
            .deletBtn {
              position: absolute;
              z-index: 1;
              left: -71px;
              cursor: pointer;
            }
            .el-input {
              flex: 1;
              &:nth-child(2) {
                margin-right: 10px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
